package com.ml.mall.service.asyn;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ml.mall.bean.req.company.CompanyNewDto;
import com.ml.mall.bean.req.company.CompanyRegisterDto;
import com.ml.mall.bean.req.company.CompanySendVerificCode;
import com.ml.mall.bean.req.credit.CreditEditDto;
import com.ml.mall.bean.req.credit.CreditNewDto;
import com.ml.mall.bean.req.credit.CreditQueryOneDto;
import com.ml.mall.bean.req.partner.PartnerDto;
import com.ml.mall.bean.req.partner.PartnerNewDto;
import com.ml.mall.bean.req.sys.SysUserDto;
import com.ml.mall.bean.req.sys.SysUserForgetPasswdEmail;
import com.ml.mall.bean.res.credit.CreditQueryInfoRes;
import com.ml.mall.consts.CommonConsts;
import com.ml.mall.consts.MailContentConsts;
import com.ml.mall.entity.company.SysCompany;
import com.ml.mall.entity.credit.SysCredit;
import com.ml.mall.entity.notifation.SysANotifation;
import com.ml.mall.entity.sys.SysUser;
import com.ml.mall.model.MailMessage;
import com.ml.mall.security.JwtUtil;
import com.ml.mall.service.company.SysCompanyService;
import com.ml.mall.service.credit.SysCreditService;
import com.ml.mall.service.mail.MailService;
import com.ml.mall.service.notifation.SysANotifationService;
import com.ml.mall.service.sys.SysUserService;
import com.ml.mall.utils.MailUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * Created by kyyang on 2021/7/27 23:25
 */
@Component
public class AuthMailServiceImplAsyn {

    @Autowired
    private MailService mailService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysCompanyService sysCompanyService;

    @Autowired
    private SysCreditService sysCreditService;

    @Autowired
    private SysANotifationService sysANotifationService;


    /**
     * @description: 买卖家注册邮件发送，通知管理员
     * @author kyyang
     * @date 2021/7/28 23:06
     * @version 1.0
     */
    @Async
    public void registerCompanyEmailAsyn(CompanyRegisterDto dto) {


        String companyName = dto.getCompanyName();
        Integer companyType = dto.getCompanyType();

        MailMessage mailMessage = null;

        //买家
        if(CommonConsts.ROLE_TYPE_PURCHASE.equals(companyType)){
             mailMessage = mailService.sendForPurchaserRegistration("");
        }
        //卖家
        if(CommonConsts.ROLE_TYPE_SUPPLIER.equals(companyType)){
            mailMessage = mailService.sendForSupplierRegistration("");
        }
        if(mailMessage==null){
            return;
        }
        mailMessage.setContent(mailMessage.getContent().replace("company_name",companyName));
        mailMessage.setContent(mailMessage.getContent().replaceAll("system_url",MailContentConsts.SYSTEM_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl",MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));

        if(mailMessage!=null){
            //通知管理员
            sysANotifationService.notifyAdmin(mailMessage);
            //发送邮件
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("role_type",CommonConsts.ROLE_TYPE_ADMIN);

            wrapper.in("role_id", Arrays.asList(new Integer[]{1,2,4,5}));
            List<SysUser> list = sysUserService.list(wrapper);
            String content=mailMessage.getContent();
            if(list!=null&&list.size()>0){
                for(SysUser u:list){
                    mailMessage.setReceiverEmail(u.getEmail());
                    mailMessage.setContent(mailMessage.getContent().replace("admin_name",u.getName()));
                    MailUtils.doSendEmail1(mailMessage);
                    mailMessage.setContent(content);
                }
            }
        }
    }

    /**
     * @description: 邀请合伙人，无通知
     * @author kyyang
     * @date 2021/7/28 23:05
     * @version 1.0
     */
    @Async
    public void inviterPartenerAsyn(PartnerDto dto) {
        sendForRegistrationInvitationFromPartner(dto);
    }

    /**
     * @description: 合作商邀请商户，无通知
     * @author kyyang
     * @date 2021/8/5 23:32
     * @version 1.0
     */
    private void sendForRegistrationInvitationFromPartner(PartnerDto dto) {
        MailMessage mailMessage = mailService.sendForRegistrationInvitationFromPartner(dto.getPartnerEmail());
        String registUrl = MailContentConsts.SYSTEM_REGISTRATION_URL+dto.getInviteCode();
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        mailMessage.setContent(mailMessage.getContent().replace("sysRegisterUrl",registUrl));
        mailMessage.setContent(mailMessage.getContent().replace("partner_name",dto.getCompanyName()));
        MailUtils.doSendEmail1(mailMessage);
    }

    /**
     * @description: 额度调整邮件发送，通知对应商户
     *
     * @author kyyang
     * @date 2021/7/28 23:06
     * @version 1.0
     */
    @Async
    public void updateCreditMailAsyn(SysUser currentUser, Long companyId, BigDecimal initialBalance, BigDecimal finalBalance) {
        String name = currentUser.getName();
        QueryWrapper<SysCompany> query = new QueryWrapper<>();
        query.eq("company_id",companyId);
        SysCompany one = sysCompanyService.getOne(query);
        if(one==null){
            return;
        }

        MailMessage mailMessage = mailService.sendForCompanyCreditModified("");

        //标题替换
        mailMessage.subjectReplace("company_name", one.getCompanyName());
        mailMessage.subjectReplace("other_admin_name", name);
        //内容替换
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));

        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        mailMessage.setContent(mailMessage.getContent().replaceAll("systemUrl",MailContentConsts.SYSTEM_URL));
        mailMessage.setContent(mailMessage.getContent().replace("other_admin_name",name));
        mailMessage.setContent(mailMessage.getContent().replace("company_name",one.getCompanyName()));
        mailMessage.setContent(mailMessage.getContent().replace("previous_credit",initialBalance.toString()));
        mailMessage.setContent(mailMessage.getContent().replaceAll("current_credit", finalBalance.toString()));

        if(mailMessage!=null){
            //通知对应商户
            sysANotifationService.notifyCompany(mailMessage,companyId);
            //发送邮件
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("company_id",companyId);
            if(one.getCompanyType().equals(CommonConsts.ROLE_TYPE_SUPPLIER)){
                wrapper.in("role_id", Arrays.asList(new Integer[]{8,9,10}));
            }else {
                //买家
                wrapper.in("role_id", Arrays.asList(new Integer[]{12,13,14}));
            }
            String content=mailMessage.getContent();
            List<SysUser> list = sysUserService.list(wrapper);
            if(list!=null&&list.size()>0){
                for(SysUser u:list){
                    mailMessage.setReceiverEmail(u.getEmail());
                    mailMessage.setContent(mailMessage.getContent().replace("admin_name",u.getName()));
                    MailUtils.doSendEmail1(mailMessage);
                    mailMessage.setContent(content);
                }
            }
            //发送邮件给管理员
            QueryWrapper<SysUser> adminUser=new QueryWrapper<>();
            adminUser.eq("role_type",CommonConsts.ROLE_TYPE_ADMIN);
            adminUser.in("role_id", Arrays.asList(new Integer[]{1,2,3,4}));
            List<SysUser> adminList = sysUserService.list(adminUser);
            if(adminList!=null&&adminList.size()>0){
                for(SysUser u:adminList){
                    mailMessage.setReceiverEmail(u.getEmail());
                    mailMessage.setContent(mailMessage.getContent().replace("admin_name",u.getName()));
                    MailUtils.doSendEmail1(mailMessage);
                    mailMessage.setContent(content);
                }
            }

        }
    }

    /**
     * @description: 买家: 用户邀请链接; 买家为自己创建完账号之后；通知对应邮箱；卖家也是一样；,无通知
     * @author kyyang
     * @date 2021/8/1 20:22
     * @version 1.0
     * @param sysUserDto
     */
    @Async
    public void userSaveMailAsyn(SysUserDto sysUserDto) {
        if(StringUtils.isNotBlank(sysUserDto.getEmail())){
            QueryWrapper<SysCompany> query = new QueryWrapper<>();
            query.eq("company_id",sysUserDto.getCompanyId());
            SysCompany one = sysCompanyService.getOne(query);
            if(one==null){
                return;
            }
            MailMessage mailMessage = mailService.sendForUserInvitationForCompany(sysUserDto.getEmail());
            mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));

            mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
            mailMessage.setContent(mailMessage.getContent().replace("user_name",sysUserDto.getName()));
            mailMessage.setContent(mailMessage.getContent().replaceAll("system_url",MailContentConsts.SYSTEM_URL));
            mailMessage.setContent(mailMessage.getContent().replace("company_name",one.getCompanyName()));
            mailMessage.setContent(mailMessage.getContent().replace("email_acc",sysUserDto.getEmail()));
            mailMessage.setContent(mailMessage.getContent().replace("user_password",sysUserDto.getPwd()));
            MailUtils.doSendEmail1(mailMessage);
        }
    }

    /**
     * @description: 卖家成功注册通知，无通知
     * @author kyyang
     * @date 2021/8/1 21:40
     * @version 1.0
     */
    @Async
    public void registeCompanyEmailAsyn(String name,String emailAddres) {
        //这里删除了买家模板；都是一样的；只使用卖家就行了
        MailMessage mailMessage = mailService.sendForRegisterSuccessfulEmail("");
        String emailVerificationUrl = MailContentConsts.EMAIL_VERIFICATION_URL+emailAddres;
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        mailMessage.setContent(mailMessage.getContent().replace("company_name",name));
        mailMessage.setContent(mailMessage.getContent().replace("emailVerificationUrl",emailVerificationUrl));
        mailMessage.setReceiverEmail(emailAddres);
        MailUtils.doSendEmail1(mailMessage);
    }


    /**
     * @description: 增加额度通知；公司公用
     * @author kyyang
     * @date 2021/8/1 21:53
     * @version 1.0
     */
    @Async
    public void creditEditEmail(SysCredit sysCredit, CreditEditDto dto) {
        if(sysCredit!=null){
            Double creditBalance = sysCredit.getCreditBalance().doubleValue();
            double v = dto.getCredit().doubleValue();
            QueryWrapper<SysCompany> query = new QueryWrapper<>();
            query.eq("company_id",sysCredit.getCompanyId());
            SysCompany sysCompany = sysCompanyService.getOne(query);
            if(v>creditBalance){
                MailMessage mailMessage = mailService.sendForCreditNotification("");
                mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
                mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
                mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
                mailMessage.setContent(mailMessage.getContent().replaceAll("system_url",MailContentConsts.SYSTEM_URL));
                mailMessage.setContent(mailMessage.getContent().replaceAll("current_credit",dto.getCredit()+""));
                if(mailMessage!=null){
                    //通知对应商户
                    sysANotifationService.notifyCompany(mailMessage, sysCredit.getCompanyId());
                    //发送邮件
                    QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
                    wrapper.eq("company_id",sysCredit.getCompanyId());
                    if(sysCompany.getCompanyType().equals(CommonConsts.ROLE_TYPE_SUPPLIER)){
                        wrapper.in("role_id", Arrays.asList(new Integer[]{8,9,10}));
                    }else{
                        wrapper.in("role_id", Arrays.asList(new Integer[]{12,13,14}));
                    }
                    mailMessage.setContent(mailMessage.getContent().replace("company_name",sysCompany.getCompanyName()));
                    List<SysUser> list = sysUserService.list(wrapper);
                    if(list!=null&&list.size()>0){
                        for(SysUser u:list){
                            mailMessage.setReceiverEmail(u.getEmail());
                            MailUtils.doSendEmail1(mailMessage);
                        }
                    }
                }
            }
        }
    }


    /**
     * @description: 邮件】：卖家：公司被批准；无通知
     * @author kyyang
     * @date 2021/8/1 22:09
     * @version 1.0
     */
    @Async
    public void editCompanyEmailCompany(SysCompany dbSysCompany, Integer state) {
        if(dbSysCompany == null || StringUtils.isBlank(dbSysCompany.getEmailAddress())){
            return;
        }
        //未发生改变；返回
        if(dbSysCompany.getState().equals(state)){
            return;
        }
        //公司被批准相关的邮件
        if(CommonConsts.STATE_NORMAL.equals(state)){
            //如果是卖家公司被批准
            if(CommonConsts.ROLE_TYPE_SUPPLIER.equals(dbSysCompany.getCompanyType())){
                //异步通知合伙人，仅卖家有合伙人
                sendForInvitedSupplierApproved(dbSysCompany);
            }
            //通知对应的公司：买卖通用
            MailMessage mailMessage = mailService.sendForAccountApproval(dbSysCompany.getEmailAddress());
            mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
            mailMessage.setContent(mailMessage.getContent().replace("company_name",dbSysCompany.getCompanyName()));
            MailUtils.doSendEmail1(mailMessage);
        }
        //公司被禁用的相关邮件
        if(CommonConsts.STATE_FORBI.equals(state)){
           //通用公司被禁用模板
           sendForCompanySuspended(dbSysCompany);
        }
    }

    /**
     * @description: 卖家公司被禁用的邮件，通知对应商户
     * @author kyyang
     * @date 2021/8/5 23:12
     * @version 1.0
     */
    private void sendForCompanySuspended(SysCompany dbSysCompany) {
        MailMessage mailMessage = mailService.sendForCompanySuspended("");
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        mailMessage.setContent(mailMessage.getContent().replace("company_name",dbSysCompany.getCompanyName()));
        if(mailMessage!=null){
            //通知对应商户
            sysANotifationService.notifyCompany(mailMessage, dbSysCompany.getCompanyId());
            //发送邮件
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("company_id",dbSysCompany.getCompanyId());

            //买家家公司被禁用的邮件
            if(CommonConsts.ROLE_TYPE_PURCHASE.equals(dbSysCompany.getCompanyType())){
                //买家
                wrapper.in("role_id", Arrays.asList(new Integer[]{12,13}));
            }else{
                wrapper.in("role_id", Arrays.asList(new Integer[]{8,9}));
            }
            List<SysUser> list = sysUserService.list(wrapper);
            if(list!=null&&list.size()>0){
                for(SysUser u:list){
                    mailMessage.setContent(mailMessage.getContent().replace("user_name",u.getName()));
                    mailMessage.setReceiverEmail(u.getEmail());
                    MailUtils.doSendEmail1(mailMessage);
                }
            }
        }
    }

    /**
     * @description: 发送被邀请的卖家被批准的邮件给合作商，通知对应合作商
     * @param dbSysCompany
     */
    @Async
    public void sendForInvitedSupplierApproved(SysCompany dbSysCompany) {
        if(dbSysCompany!=null){
            MailMessage mailMessage = mailService.sendForInvitedSupplierApproved("");
            //设置标题
            mailMessage.subjectReplace("company_name", dbSysCompany.getCompanyName());
            //设置内容
            mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("system_url",MailContentConsts.SYSTEM_URL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
            if(mailMessage!=null){
                //获取对应合作商
                LambdaQueryWrapper<SysCompany> companyWrapper = new LambdaQueryWrapper<>();
                companyWrapper.eq(SysCompany::getInviteCode, dbSysCompany.getRegistartionNo());
                SysCompany partnerCompany = sysCompanyService.getOne(companyWrapper);

                if(partnerCompany!=null){
                    //通知对应合作商
                    sysANotifationService.notifyCompany(mailMessage, partnerCompany.getCompanyId());
                    //发送邮件
                    //获取合作商下的用户
                    LambdaQueryWrapper<SysUser> userWrapper = new LambdaQueryWrapper<>();
                    userWrapper.in(SysUser::getRoleId, Arrays.asList(new Integer[]{6,7}))
                            .eq(SysUser::getCompanyId, partnerCompany.getCompanyId());
                    List<SysUser> list = sysUserService.list(userWrapper);
                    if(list!=null&&list.size()>0){
                        for(SysUser u:list){
                            mailMessage.setContent(mailMessage.getContent().replace("partner_name",partnerCompany.getCompanyName()));
                            mailMessage.setContent(mailMessage.getContent().replace("company_name",dbSysCompany.getCompanyName()));
                            mailMessage.setReceiverEmail(u.getEmail());
                            MailUtils.doSendEmail1(mailMessage);
                        }
                    }
                }
            }
        }
    }

    /**
     * @description: 邮件：合作商点击邀请链接；注册合作商；通知管理员
     * @author kyyang
     * @date 2021/8/1 22:30
     * @version 1.0
     */
    @Async
    public void createPartnerMailAsyn(PartnerNewDto dto) {
        if(dto!=null){
            MailMessage mailMessage = mailService.sendForPartnerOnBoard("");
            mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("system_url",MailContentConsts.SYSTEM_URL));
            mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
            if(mailMessage!=null){
                //通知管理员
                sysANotifationService.notifyAdmin(mailMessage);
                //发送邮件
                QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
                wrapper.in("role_id", Arrays.asList(new Integer[]{1,2}));
                List<SysUser> list = sysUserService.list(wrapper);
                if(list!=null&&list.size()>0){
                    for(SysUser u:list){
                        mailMessage.setContent(mailMessage.getContent().replace("admin_name", u.getName()));
                        mailMessage.setContent(mailMessage.getContent().replace("company_name",dto.getCompanyName()));
                        mailMessage.setReceiverEmail(u.getEmail());
                        MailUtils.doSendEmail1(mailMessage);
                    }
                }
            }
        }
    }

    /**
     * @description: 【邮件】注册验证吗,无通知
     * @author kyyang
     * @date 2021/8/2 22:35
     * @version 1.0
     */
    @Async
    public void companyRegisterSendVerificCodeMailAsyn(String code, CompanySendVerificCode dto) {
        MailMessage mailMessage = mailService.sendVerifyCode(code, dto.getEmail());
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
        mailMessage.setContent(mailMessage.getContent().replace("user_name", ""));
        MailUtils.doSendEmail1(mailMessage);
    }

    /**
     * @description: 忘记密码发送邮件，无通知
     * @author kyyang
     * @date 2021/8/2 22:51
     * @version 1.0
     */
    @Async
    public void forgetPasswd2Email(String code, SysUserForgetPasswdEmail sysUserForgetPasswdEmail,SysUser currentUser) {
        MailMessage mailMessage = mailService.sendForResetPassword( sysUserForgetPasswdEmail.getAcc());
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        mailMessage.setContent(mailMessage.getContent().replace("user_name", currentUser.getName()));
        mailMessage.setContent(mailMessage.getContent().replace("generated_code", code));
        MailUtils.doSendEmail1(mailMessage);
    }

    /**
     * 发送合作商邀请链接邮件给合作商，无通知
     * @param dto
     */
    @Async
    public void partnerInviterMailAsyn(PartnerDto dto) {
        //String name = currentUser.getName();
        MailMessage mailMessage = mailService.sendForPartnerInvitationLink(dto.getPartnerEmail());
        mailMessage.setContent(mailMessage.getContent().replaceAll("mainPicUrl", MailContentConsts.MAIN_PIC_URL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("general_email",MailContentConsts.GENERAL_EMAIL));
        mailMessage.setContent(mailMessage.getContent().replaceAll("contact_no",MailContentConsts.CONCAT));
        MailUtils.doSendEmail1(mailMessage);
    }
}
